package com.haidechizi.validate.holder;

import com.haidechizi.validate.dict.Dict;
import com.haidechizi.validate.dict.service.DictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DictHolder implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private DictService dictService;

    private static final Map<String, Set<String>> valueHolder = new HashMap<>(64);

    private static final Map<String, String> messageHolder = new HashMap<>(64);

    private volatile boolean init = false;

    private static final Pattern pattern = Pattern.compile("<.*>");

    public void init() {
        List<Dict> dictList = dictService.dictList();
        doInit(dictList);
    }

    public void doInit(List<Dict> dictList) {
        if (CollectionUtils.isEmpty(dictList)) {
            return;
        }
        Map<String, List<String>> labelMap = new HashMap<>();
        dictList.forEach(dict -> {
            // 构建value的map
            Set<String> values = valueHolder.get(dict.getType());
            if (values == null) {
                values = new HashSet<>();
                valueHolder.put(dict.getType(), values);
            }
            values.add(dict.getValue());

            List<String> labels = labelMap.get(dict.getType());
            if (labels == null) {
                labels = new ArrayList<>();
                labelMap.put(dict.getType(), labels);
            }
            labels.add(dict.getLabel());
        });

        // 构建消息体
        for (Map.Entry<String, Set<String>> entry : valueHolder.entrySet()) {
            messageHolder.put(entry.getKey(), entry.getValue().toString());
        }

        for (Map.Entry<String, List<String>> entry : labelMap.entrySet()) {
            messageHolder.put(entry.getKey() + "#label", entry.getValue().toString());
        }
    }

    public static final Set<String> getValues(String key) {
        return Optional.ofNullable(valueHolder.get(key)).orElse(new HashSet<>());
    }

    public static final String getMessage(String message) {
        Matcher matcher = pattern.matcher(message);
        while (matcher.find()) {
            String group = matcher.group();
            String replace = group.replace("<", "").replace(">", "");
            String msg = messageHolder.get(replace);
            message = message.replaceAll(group, msg);
            matcher = pattern.matcher(message);
        }
        return message;
    }


    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        if (!init) {
            init();
        }
    }
}
